<template>
  <div class="default_main">
    <HomeBanner :banner="[{ image: '/src/assets/Home/default_banner.jpg' }]" />
    <BannerAdv :index_adv="[{ image: '/src/assets/Home/banner_b1.jpg' }, { image: '/src/assets/Home/banner_b2.jpg' }, { image: '/src/assets/Home/banner_b3.jpg' }]" />
    <div class="index_bg">
      <!--一级分类-->
      <div class="goods_class_list w1200" v-for="(v, k) in cateStore.goodsCategoryList" :key="k">
        <AdvView :adv="{ image: '/src/assets/Home/adv.jpg' }" />
        <div>
          <div class="title">
            {{ v.name || '加载中...' }}<span><router-link :to="`/home/goods/category/${v.id}`">查看更多</router-link></span>
          </div>
          <div class="index_adv_goods_left">
            <el-image lazy fit="cover" src="/src/assets/Home/pc_class_btadv.jpg" alt="名字" />
          </div>
          <!-- 商品列表 -->
          <div class="index_class_goods_right">
            <ul>
              <li v-for="(vo, key) in categoryGoodsLists[v.id]?.slice(0, 8)" :key="key">
                <div class="product_act_in">
                  <RouterLink :to="`/home/goods/detail/${vo.id}`" class="product_act_in">
                    <dl>
                      <dt>
                        <!--       这里是一个由逗号分隔的多个字符串，所以必须转换，不能直接使用第一张图                 <el-image class="el_image" lazy fit="cover" :src="vo.imgUrl||''" :alt="vo.name" />-->
                        <el-image class="el_image" lazy fit="cover" :src="getFirstImageUrl(vo.imgUrl) || ''" :alt="vo.name" />
                      </dt>
                      <dd class="product_title" :title="vo.name">{{ vo.name }}</dd>
                      <dd class="product_subtitle">{{ vo.subName }}</dd>
                      <dd class="product_price">
                        ￥{{ vo.price }}<span>{{ vo.oldPrice }}元</span>
                      </dd>
                    </dl>
                  </RouterLink>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <!-- 展示更多商品-->
      <div class="goods_class_list w1200">
        <GoodsItem />
      </div>
    </div>
  </div>
</template>
<script setup name="HomeIndex" lang="ts">
import HomeBanner from './components/HomeBanner.vue';
import BannerAdv from '@/components/Home/BannerAdv.vue';
import AdvView from '@/components/Home/Adv.vue';
import { useCategoryStore } from '@/store';
import { ref, watchEffect } from 'vue';
import type { MallGoodsVO } from '@/api/home/mallGoods/types';
import { cate1IdApi } from '@/api/home/index';
import GoodsItem from '@/components/GoodsItem/index.vue';

const cateStore = useCategoryStore();
const categoryGoodsLists = ref<Record<number, MallGoodsVO[]>>({});

// 监听分类列表的变化，并加载对应的商品列表
watchEffect(() => {
  if (!cateStore.goodsCategoryList.length) return; // 如果没有分类，则不执行
  const promises = cateStore.goodsCategoryList.map(async (category) => {
    try {
      const response = await cate1IdApi(category.id); // 调用API获取商品列表
      if (!response || !response.data) {
        throw new Error('Error' + category.id);
      }
      return { categoryId: category.id, goods: response.data }; // 返回分类ID和商品列表
    } catch (error) {
      console.error('Error' + category.id, error);
      throw error; // 重新抛出错误，以便在Promise.all的catch中捕获
    }
  });

  // 等待所有请求完成
  Promise.all(promises)
    .then((results) => {
      // 创建一个新的对象来存储分类和商品列表的映射
      const newCategoryGoodsLists: any = {};
      results.forEach((result) => {
        newCategoryGoodsLists[result.categoryId] = result.goods;
      });
      // 使用新的映射更新categoryGoodsLists
      categoryGoodsLists.value = newCategoryGoodsLists;
      // 所有商品列表都已加载完毕，可以在这里做一些处理（如果需要）
    })
    .catch((error) => {
      console.error('Failed:', error);
      // 可以选择在这里处理错误，比如显示一个错误消息给用户
    });
});
/*取第一张图片*/
const getFirstImageUrl = (imageUrls: string) => {
  const image = imageUrls.split(',');
  return image.length > 0 ? image[0] : '@/assets/images/none.png';
};
</script>
<style scoped lang="scss">
.index_bg {
  background: #f5f5f5;
  padding: 20px 0 60px 0;
  margin-top: 40px;
}

.index_class_goods_right {
  width: 966px;
  float: left;

  ul li {
    cursor: pointer;
    width: 220px;
    height: 300px;
    margin-bottom: 14px;
    margin-left: 20px;
    box-sizing: border-box;
    float: left;

    .product_act_in {
      width: 220px;
      height: 300px;
      background: #fff;
      box-sizing: border-box;
      transition: all 0.2s linear;

      .el_image {
        width: 140px;
        height: 140px;
      }
    }

    dl {
      padding-top: 20px;
    }

    dl dt {
      width: 140px;
      height: 140px;
      margin: 0 auto;
    }

    dl dt img {
      width: 140px;
      height: 140px;
    }

    dl dd {
      width: 190px;
      overflow: hidden;
      text-align: center;
      margin: 0 auto;
    }

    dl dd.product_title {
      font-size: 14px;
      margin-top: 25px;
      height: 30px;
      line-height: 30px;
    }

    dl dd.product_subtitle {
      margin-top: 0px;
      font-size: 12px;
      color: #b0b0b0;
      line-height: 14px;
    }

    dl dd.product_price {
      margin-top: 10px;
      font-size: 16px;
      color: #ca151e;
      line-height: 34px;

      span {
        font-size: 14px;
        color: #b0b0b0;
        margin-left: 8px;
        text-decoration: line-through;
      }
    }
  }

  ul li:hover .product_act_in {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: -3px;
  }
}

.index_adv_goods_left {
  width: 234px;
  height: 614px;
  float: left;
  transition: all 0.2s linear;
  background: #fff;
}

.index_adv_goods_left:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.goods_class_list:after {
  clear: both;
  display: block;
  content: '';
}

.goods_class_list {
  margin-bottom: 30px;

  .title {
    font-size: 22px;
    margin-bottom: 20px;

    span {
      font-size: 14px;
      float: right;
    }
  }
}
</style>
